package vip.ola.pay.batchpay;

import java.io.File;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.junit.Before;
import org.junit.Test;
import vip.ola.pay.batchpay.sdk.domain.Response;
import vip.ola.pay.batchpay.sdk.pay.PaymentHelper;
import vip.ola.pay.batchpay.sdk.pay.domain.cashierPay.*;
import vip.ola.pay.batchpay.sdk.pay.domain.nativePay.NativePayRequest;
import vip.ola.pay.batchpay.sdk.pay.domain.nativePay.NativePayResponse;
import vip.ola.pay.batchpay.sdk.pay.domain.paymenQuery.PaymentQueryRequest;
import vip.ola.pay.batchpay.sdk.pay.domain.protocol.ProtocolPayBindCardRequest;
import vip.ola.pay.batchpay.sdk.pay.domain.protocol.ProtocolPayBindCardResponse;
import vip.ola.pay.batchpay.sdk.pay.domain.withdraw.CustomerAccountQueryResp;
import vip.ola.pay.batchpay.sdk.pay.domain.withdraw.WithdrawToCardQueryResponse;
import vip.ola.pay.batchpay.sdk.pay.domain.withdraw.WithdrawToCardRequest;
import vip.ola.pay.batchpay.sdk.pay.domain.withdraw.WithdrawToCardResponse;
import vip.ola.pay.batchpay.sdk.utils.Config;
import vip.ola.pay.batchpay.sdk.utils.RsaUtils;


public class EfpsTest {

	static final String NOTIFY_URL = "http://127.0.0.1:8080/demo/notify";// 异步通知结果地址

	private String customerCode2 = Config.getSplitCustomerCode(); //

	@Before
	public void initialize() throws URISyntaxException {
		Config.initialize(new File(ClassLoader.getSystemResource("config_test.properties").toURI()));
		System.setProperty("sdk.mode", "debug");
	}

	@Test
	public void mainTest() throws Exception {


		// withdrawalToCardQuery();//单笔代付查询
//		 withdrawalToCard();//单笔代付
		// accountQuery();//余额查询
		cashierPay();
//		bindCard();
	}


	/**
	 * 统一下单接口（不包含分账）
	 */
	public Response cashierPay() throws Exception {

		String version = "3.0";
		String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
		String outTradeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); // 交易编号,商户侧唯一
		String customerCode = Config.getCustomerCode(); //
		// 商户编号
		String clientIp = "127.0.0.1"; // IP
		long payAmount = 2000; // 支付金额,分为单位
		String payCurrency = "CNY"; // 币种，写死
		String notifyUrl = "http://www.baidu.com/a.php"; // 异步通知地址
		String redirectUrl = "http://www.baidu.com"; // 同步通知地址
		String attachData = "attachData"; // 备注数据,可空
		String transactionStartTime = Config.getTransactionStartTime(); // 交易开始时间
		String transactionEndTime = ""; // 交易结束时间
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setId("test");
		orderInfo.setBusinessType("test");
		orderInfo.addGood(new OrderGoods("订单信息", "1箱...", 1));// 填写真实的订单信息如new
		// OrderGoods("订单信息",
		// "1箱", 1)
		CashierRequest order = new CashierRequest(version, outTradeNo, customerCode, clientIp, orderInfo, payAmount,
				payCurrency, redirectUrl, attachData, transactionStartTime, transactionEndTime, nonceStr);
		order.setNotifyUrl(notifyUrl);
		// 终端信息
		TerminalInfo terminalInfo = new TerminalInfo();
		terminalInfo.setTerminal_type("17");
		terminalInfo.setTerminal_id("70054167");
		terminalInfo.setApp_version("1.0");
		terminalInfo.setTerminal_ip("127.0.0.1");
		// order.setTerminalInfo(terminalInfo);
		// 地区信息
		order.setAreaInfo("440106");

		// ----分账设置，如需分账，一定要传true
		order.setNeedSplit(false);
		// 是否限制信用卡支付，不填默认是false(即不限制)
		order.setNoCreditCards(false);
		CashierResponse response = PaymentHelper.cashierPay(order);
		System.out.println("收银台订购地址：" + response.getCasherUrl());
		return response;
	}

	/**
	 * 主扫支付
	 */
	public Response nativePay() throws Exception {
		String version = "3.0";
		String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
		String outTradeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); // 交易编号,商户侧唯一
		String customerCode = Config.getCustomerCode(); // 商户编号
		String clientIp = "127.0.0.1"; // IP
		long payAmount = 5; // 支付金额,分为单位
		String payCurrency = "CNY"; // 币种，写死
		String notifyUrl = "http://www.baidu.com"; // 异步通知地址
		String redirectUrl = "http://www.baidu.com"; // 同步通知地址
		String attachData = "attachData"; // 备注数据,可空
		String transactionStartTime = Config.getTransactionStartTime(); // 交易开始时间
		String transactionEndTime = ""; // 交易结束时间
		String payMethod = "7";// 6：微信主扫支付 7：支付宝主扫支付 24：银联二维码主扫
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setId("test");
		orderInfo.setBusinessType("test");
		orderInfo.addGood(new OrderGoods("订单信息", "1箱", 1));// 填写真实的订单信息如new
		// OrderGoods("订单信息",
		// "1箱", 1)

		NativePayRequest order = new NativePayRequest(version, outTradeNo, customerCode, clientIp, orderInfo, payAmount,
				payCurrency, notifyUrl, redirectUrl, attachData, transactionStartTime, transactionEndTime, payMethod,
				nonceStr);

		// ----分账设置，注意分账金额总和等于交易金额-----
		List<SplitInfo> splitInfoList = new ArrayList<SplitInfo>();
		splitInfoList.add(new SplitInfo(Config.getCustomerCode(), 50, 3));
		splitInfoList.add(new SplitInfo(customerCode2, 9950, 0));

		// 终端信息
		TerminalInfo terminalInfo = new TerminalInfo();
		terminalInfo.setTerminal_type("17");
		terminalInfo.setTerminal_id("70054167");
		terminalInfo.setApp_version("1.0");
		terminalInfo.setTerminal_ip("127.0.0.1");
		// order.setTerminalInfo(terminalInfo);
		// 地区信息
		order.setAreaInfo("440106");
		// order.setNeedSplit(true);// 不填默认否，只有开通了分账业务的商户才可将该值设置为true
		// order.setSplitModel("1");
		// order.setSplitMain(customerCode);
		// order.setSplitInfoList(splitInfoList);
		// order.setSplitNotifyUrl("http://www.baidu.com");//非必填
		// order.setSplitAttachData(UUID.randomUUID().toString().replaceAll("-",
		// ""));//非必填
		// ----分账设置-----

		// 是否限制信用卡支付，不填默认是false(即不限制)
		// order.setNoCreditCards(false);
		NativePayResponse response = PaymentHelper.nativePay(order);

		return response;
	}




	/**
	 * 单笔代付 单笔提现
	 * 
	 * @return
	 * @throws Exception
	 */
	public Response withdrawalToCard() throws Exception {

		String outTradeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); // 交易编号,商户侧唯一
		// String customerCode = "";
		long payAmount = 10;
		String payCurrency = "CNY";
		String notifyUrl = NOTIFY_URL + "/WithdrawalForSubMerchant";
		String remark = "这是附言";

		String publicKeyPath = Config.getPublicKeyFile().getAbsolutePath();

		String bankUserName = RsaUtils.encryptByPublicKey("哎哎哎", RsaUtils.getPublicKey(publicKeyPath));
		// String bankUserCert = RsaUtils.encryptByPublicKey("3623xxxx234324",
		// RsaUtils.getPublicKey(publicKeyPath));
		String bankCardNo = RsaUtils.encryptByPublicKey("6214830201234567", RsaUtils.getPublicKey(publicKeyPath));
		// 6225882014447885
		WithdrawToCardRequest request = new WithdrawToCardRequest();
		request.setOutTradeNo(outTradeNo);
		request.setCustomerCode(Config.getCustomerCode());
		request.setAmount(payAmount);
		request.setIsAdvanceFund("");

		request.setBankUserName(bankUserName);
		// request.setBankUserCert(bankUserCert);
		request.setBankCardNo(bankCardNo);
		// request.setBankNo("102xxx0012");//联行号
		request.setBankName("招商银行");
		request.setBankProvince("广东省");
		request.setBankCity("广州市");
		request.setBankSub("广州支行");
		request.setBankAccountType("2");// 1：对公，2：对私
		request.setPayCurrency(payCurrency);
		request.setNotifyUrl(notifyUrl);
		request.setRemark(remark);
		request.setIsFullAmount(0);// isFullAmount 是否全额代付 Integer 否 0：非全额代付，默认值;
									// 1：全额代付 ;
									// amount有值时，isFullAmount参数不做检查，amount无值时，isFullAmount必需=1，否则报文错误
		request.setNonceStr(UUID.randomUUID().toString().replaceAll("-", ""));

		WithdrawToCardResponse response = PaymentHelper.withdrawalToCard(request);

		return response;
	}

	/**
	 * 单笔代付结果查询
	 * 
	 * @return
	 * @throws Exception
	 */
	public Response withdrawalToCardQuery() throws Exception {

		PaymentQueryRequest request = new PaymentQueryRequest();
		request.setCustomerCode(Config.getCustomerCode());// 必填
		// 交易订单号和商户号订单号，选填其中任一项。如果两个都填，以交易订单号为准
		request.setTransactionNo("TX201809171119463009002");
		request.setOutTradeNo("");
		request.setNonceStr(UUID.randomUUID().toString().replaceAll("-", ""));
		WithdrawToCardQueryResponse response = PaymentHelper.withdrawalToCardQuery(request);

		return response;
	}



	/**
	 * 余额查询
	 * 
	 * @return
	 * @throws Exception
	 */
	public Response accountQuery() throws Exception {

		Map<String, String> request = new HashMap<String, String>();
		request.put("customerCode", Config.getCustomerCode());
		request.put("nonceStr", UUID.randomUUID().toString().replaceAll("-", ""));
		request.put("accountType", "3");
		CustomerAccountQueryResp response = PaymentHelper.accountQuery(request);

		return response;
	}

	/**
	 * 协议支付绑卡预交易
	 *
	 * @return
	 * @throws Exception
	 */
	public Response bindCard() throws Exception {

		String outTradeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); // 交易编号,商户侧唯一
		// String customerCode = "";
		long payAmount = 10;
		String payCurrency = "CNY";
		String notifyUrl = NOTIFY_URL + "/WithdrawalForSubMerchant";
		String remark = "";

		String publicKeyPath = Config.getPublicKeyFile().getAbsolutePath();

		String cvn = RsaUtils.encryptByPublicKey("672", RsaUtils.getPublicKey(publicKeyPath));
		// 2018年2月
		String expired = RsaUtils.encryptByPublicKey("2209", RsaUtils.getPublicKey(publicKeyPath));

		String userName = RsaUtils.encryptByPublicKey("com", RsaUtils.getPublicKey(publicKeyPath));
		String certificatesNo = RsaUtils.encryptByPublicKey("310115197803261111", RsaUtils.getPublicKey(publicKeyPath));
		String bankCardNo = RsaUtils.encryptByPublicKey("6224243000000011", RsaUtils.getPublicKey(publicKeyPath));
		String phoneNum = RsaUtils.encryptByPublicKey("13222222222", RsaUtils.getPublicKey(publicKeyPath));

		ProtocolPayBindCardRequest request = new ProtocolPayBindCardRequest();

		request.setCustomerCode(Config.getCustomerCode());
		request.setMemberId("mb201811300002");// 会员号
		request.setMchtOrderNo(outTradeNo);
		request.setPhoneNum(phoneNum);// 手机号
		request.setUserName(userName);// 持卡人姓名
		request.setBankCardNo(bankCardNo);// 银行卡
		request.setBankCardType("debit");// debit:借记卡,credit:贷记卡;
		request.setCvn(cvn);// cvn 卡背后三位数 信用卡必填
		request.setExpired(expired);// 卡有效期 信用卡必填 yymm
		request.setCertificatesNo(certificatesNo);// 身份证号
		request.setCertificatesType("01");// 固定传01
		request.setNonceStr(UUID.randomUUID().toString().replaceAll("-", ""));

		ProtocolPayBindCardResponse response = PaymentHelper.bindCard(request);
		System.out.println("SmsNo：" + response.getSmsNo());

		return response;
	}



}
